#include "key.h"

void key_init(void)			//按键初始化
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStructure);
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
}

uint8_t KEY_Scan(void)
{
	uint8_t key=0;
	if(KEY_UP==0 || KEY_DOWN==0 || KEY_LEFT==0 || KEY_RIGHT==0 || KEY_START==0)
	{
		Delay_ms(10);
		
		if(KEY_UP==0)			key = 1;
		else if(KEY_DOWN==0)	key = 2;
		else if(KEY_LEFT==0)	key = 3;
		else if(KEY_RIGHT==0)	key = 4;
		else if(KEY_START==0)	key = 5;
		
		while(KEY_UP==0 || KEY_DOWN==0 || KEY_LEFT==0 || KEY_RIGHT==0 || KEY_START==0);
	}
	return key;
}

void key_exti_init(void)		//按键外部中断初始化
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);

	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&GPIO_InitStructure);
	
	EXTI_InitTypeDef EXTI_InitStructure;
	EXTI_InitStructure.EXTI_Line = EXTI_Line10;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;		
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);

	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
}

//void EXTI15_10_IRQHandler(void)
//{
//	Delay_ms(20);
//	if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_10) == RESET)
//	{
//		if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_10) == RESET)
//		{
//			led_toggle();
//		}
//	}
//	EXTI_ClearITPendingBit(EXTI_Line10);
//}


